<template>
    <div class="profile-page">

        <div class="user-info">
            <div class="container">
            <div class="row">

                <div class="col-xs-12 col-md-10 offset-md-1">
                <img :src="profile.image" class="user-img" />
                <h4>{{profile.username}}</h4>
                <p>
                   {{profile.bio}}
                </p>
                <button v-if="profile.username !== user.username" @click="follow" class="btn btn-sm btn-outline-secondary action-btn">
                    <i class="ion-plus-round"></i>
                    {{profile.following ? 'UnFollow' : 'Follow'}} {{profile.username}}
                </button>
                </div>

            </div>
            </div>
        </div>

        <div class="container">
            <div class="row">

            <div class="col-xs-12 col-md-10 offset-md-1">
                <div class="articles-toggle">
                <ul class="nav nav-pills outline-active">
                    <li class="nav-item">
                        <nuxt-link
                        class="nav-link"
                        :class="{
                            active: tab === 'my_articles'
                        }"
                        exact
                        :to="{
                            name: 'profile',
                            params: {
                                username: profile.username
                            }
                        }"
                        >My Articles</nuxt-link>
                    </li>
                    <li class="nav-item">
                        <nuxt-link
                        class="nav-link"
                        :class="{
                            active: tab === 'favorited_articles'
                        }"
                        exact
                        :to="{
                            name: 'profile',
                            params: {
                                username: profile.username
                            },
                            query: {
                                tab: 'favorited_articles'
                            }
                        }"
                        >Favorited Articles</nuxt-link>
                    </li>
                </ul>
                </div>

                <div
                    class="article-preview"
                    v-for="article in articles"
                    :key="article.slug"
                >
                    <div class="article-meta">
                    <nuxt-link :to="{
                        name: 'profile',
                        params: {
                        username: article.author.username
                        }
                    }">
                        <img :src="article.author.image" />
                    </nuxt-link>
                    <div class="info">
                        <nuxt-link class="author" :to="{
                        name: 'profile',
                        params: {
                            username: article.author.username
                        }
                        }">
                        {{ article.author.username }}
                        </nuxt-link>
                        <span class="date">{{ article.createdAt | date('MMM DD, YYYY') }}</span>
                    </div>
                    <button
                        class="btn btn-outline-primary btn-sm pull-xs-right"
                        :class="{
                        active: article.favorited
                        }"
                        @click="onFavorite(article)"
                        :disabled="article.favoriteDisabled"
                    >
                        <i class="ion-heart"></i> {{ article.favoritesCount }}
                    </button>
                    </div>
                    <nuxt-link
                    class="preview-link"
                    :to="{
                        name: 'article',
                        params: {
                        slug: article.slug
                        }
                    }"
                    >
                    <h1>{{ article.title }}</h1>
                    <p>{{ article.description }}</p>
                    <span>Read more...</span>
                    <ul class="tag-list">
                        <li class="tag-default tag-pill tag-outline" v-for="(item, index) in article.tagList" :key="index">{{item}}</li>
                    </ul>
                    </nuxt-link>
                </div>

                <!-- 分页列表 -->
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="limit"
                    layout="sizes, prev, pager, next"
                    :total="articlesCount">
                </el-pagination>
                <!-- /分页列表 -->


            </div>

            </div>
        </div>

        </div>
</template>

<script>
import { mapState } from 'vuex'
import { getProfile, followUser, unFollowUser } from '@/api/profile'
import {
    getArticles,
    getYourFeedArticles,
    addFavorite,
    deleteFavorite
  } from '@/api/article'

  export default {
    name: 'Profile',
    middleware: 'authenticated',
    async asyncData ({ params, query }) {
        const username = params.username

        const page = Number.parseInt(query.page|| 1)
        const limit = Number.parseInt(query.limit|| 20)
        const tab = query.tab || 'my_articles'

        const obj = {
                limit,
                offset: (page - 1) * limit
            }
        if(tab === 'my_articles'){
            obj.author = username
        }else{
            obj.favorited = username
        }

        const [ profileRes, articleRes ] = await Promise.all([
            getProfile(username),
            getArticles(obj)
        ])
        
        const { profile } = profileRes.data

        const { articles, articlesCount } = articleRes.data

        articles.forEach(article => article.favoriteDisabled = false)

        return {
            profile,
            articles, // 文章列表
            articlesCount, // 文章总数
            limit, // 每页大小
            page, // 页码
            tab // 选项卡
        }
    },
    watchQuery: ['page', 'tab'],
    computed: {
      ...mapState(['user'])
    },
    methods: {
        async follow() {
            const { data } = this.profile.following
            ? await unFollowUser(this.$route.params.username) //取消关注
            : await followUser(this.$route.params.username) //关注
            console.log(data)
            this.profile = data.profile
        },
        async onFavorite (article) {
            article.favoriteDisabled = true
            if (article.favorited) {
            // 取消点赞
            await deleteFavorite(article.slug)
            article.favorited = false
            article.favoritesCount += -1
            } else {
            // 添加点赞
            await addFavorite(article.slug)
            article.favorited = true
            article.favoritesCount += 1
            }
            article.favoriteDisabled = false
        },
        handleSizeChange(val) {
            this.$router.push({
                        name: 'profile',
                        query: {
                            page: 1,
                            limit: val,
                            tab: this.tab
                        },
                        params: {
                            username: this.profile.username
                        }
                    })
        },
        handleCurrentChange(val) {
            this.$router.push({
                        name: 'profile',
                        query: {
                            page: val,
                            limit: this.limit,
                            tab: this.tab
                        },
                        params: {
                            username: this.profile.username
                        }
                    })
        }
    }
  }
</script>